package Controllers

import (
	"Ahq/Models"
	"Ahq/Services"
	"Ahq/ValiEngine"
	"fmt"
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

func IndexPage(c *gin.Context) {
	maps := make([]map[string]string, 0)
	for _, r := range ValiEngine.GetAllRule() {

		map1 := make(map[string]string)
		map1["key"] = r.GetKey()
		map1["name"] = r.GetName()
		map1["desc"] = r.GetDesc()
		maps = append(maps, map1)
	}
	c.HTML(http.StatusOK, "default/index.html", gin.H{
		"rules": maps,
	})
}

type parameter struct {
	Title         string   `json:"title" binding:"required"`
	SubTitle      string   `json:"subTitle" binding:"required"`
	FormulaLength string   `json:"formulaLength" binding:"required"`
	FormulaDigit  string   `json:"formulaDigit" binding:"required"`
	SymbolTypes   []string `json:"symbolTypes"`
	Rules		[]string `binding:"required"`
}

func Preview(c *gin.Context) {
	var param parameter
	if err := c.ShouldBindBodyWith(&param, binding.JSON); err != nil {
		fmt.Printf("err: %s\n", err.Error())
		c.AbortWithStatusJSON(
			http.StatusInternalServerError,
			gin.H{"error": err.Error()})
		return
	}
	paper := getPaper(param)
	c.String(http.StatusOK, paper.GetPaper())
}
func Download(c *gin.Context) {
	f := c.Query("filename")
	fileContentDisposition := "attachment;filename=\"" + f + "\""
	c.Header("Content-Type", "application/pdf")
	c.Header("Content-Disposition", fileContentDisposition)
	c.File(f)
	defer func() {

	}()

}

func CreatePdf(c *gin.Context) {
	var param parameter
	if err := c.ShouldBindBodyWith(&param, binding.JSON); err != nil {
		fmt.Printf("err: %s\n", err.Error())
		c.AbortWithStatusJSON(
			http.StatusInternalServerError,
			gin.H{"error": err.Error()})
		return
	}
	paper := getPaper(param)
	byteBuffer, err := Services.Pdf(paper)
	if err != nil {
		fmt.Printf("err: %s\n", err.Error())
		c.AbortWithStatusJSON(
			http.StatusInternalServerError,
			gin.H{"error": err.Error()})
		return
	}
	filename := fmt.Sprint(time.Now().UnixNano(), ".pdf")
	file, _ := os.Create(filename)
	byteBuffer.WriteTo(file)
	c.String(http.StatusOK, filename)
}

func getPaper(param parameter) Models.Paper {
	var formulaConfig Services.FormulaConfig
	formulaConfig.Length, _ = strconv.Atoi(param.FormulaLength)
	t := []byte("")
	for _, v := range param.SymbolTypes {
		switch v {
		case "0":
			t = append(t, Models.Addition)
		case "1":
			t = append(t, Models.Subtraction)
		case "2":
			t = append(t, Models.Multiplication)
		case "3":
			t = append(t, Models.Division)
		}
	}
	formulaConfig.SymbolTypes = t
	formulaConfig.Digit, _ = strconv.ParseInt(param.FormulaDigit, 10, 64)

	var PaperConfig Services.PaperConfig
	PaperConfig.Title = param.Title
	PaperConfig.SubTitle = param.SubTitle
	PaperConfig.FormulaConfig = formulaConfig
	PaperConfig.Size = 100
	PaperConfig.Rules=param.Rules
	paper := Services.GeneratePaper(&PaperConfig)
	return paper
}
